<template>
  <div class="wapper">
    <div @click="show = true" class="value">
      <van-loading v-if="loading">加载中，请稍候...</van-loading>
      <template v-else>{{ text ? text : "请选择" }}</template>
    </div>

    <van-popup
      v-model="show"
      safe-area-inset-bottom
      close-on-popstate
      position="bottom"
      get-container="body"
      style="height: 50vh"
    >
      <van-empty
        v-if="!loading && list.length < 1"
        :image="require('@/assets/empty.svg')"
        description="暂无数据"
      />

      <tree v-else :list="list" @change="onChange" />
    </van-popup>
  </div>
</template>

<script>
import { Popup, Loading, Empty } from "vant";
import { GetAreaTree } from "@/api/check";
import Tree from "./Tree";
import { to } from "@/utils";

export default {
  name: "AreaTree",
  components: {
    [Popup.name]: Popup,
    [Loading.name]: Loading,
    [Empty.name]: Empty,
    [Tree.name]: Tree,
  },
  model: {
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      required: true,
    },
    samplePointAttributeName: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      list: [],
      show: false,
      loading: false,
      token: "",
    };
  },
  watch: {
    samplePointAttributeName(val) {
      if (val) {
        this.text = val;
      }
    },
  },
  computed: {
    valueMirror: {
      get: function () {
        return this.value;
      },
      set: function (val) {
        this.$emit("change", val);
      },
    },
    text() {
      const value = this.valueMirror;
      let rText = "";
      const recursiveTree = (array) => {
        array.forEach(({ code, name, children }) => {
          if (value === code) {
            rText = name;
            return false;
          } else if (Array.isArray(children) && children.length) {
            recursiveTree(children);
          }
        });
      };
      recursiveTree(this.list);
      return rText;
    },
  },
  methods: {
    onChange({ code }) {
      this.valueMirror = code;
      this.$nextTick(() => (this.show = false));
    },
    async fetchItems() {
      this.loading = true;
      var params = {
        pageModel: { Token: this.token, Search: ["area"] },
      };

      const [err, res] = await to(GetAreaTree(params));
      this.loading = false;
      if (err) return;
      var rows = res.Result;

      this.list = rows;
    },
  },
  created() {
    this.token = localStorage.getItem("tokenKey");
    this.fetchItems();
  },
};
</script>

<style lang="less" scoped>
.wapper,
.value {
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>